package com.zh.note.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: zhanghuan
 * @date: 2025/8/26 00:19
 * @description: create it
 */
@Configuration
public class ThreadPoolConfig {

    @Resource
    private ThreadPoolProperties threadPoolProperties;

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        // 创建线程池任务执行器实例
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 设置核心线程数，线程池中保持的最小线程数量
        threadPoolTaskExecutor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        // 设置最大线程数，线程池中允许创建的最大线程数量
        threadPoolTaskExecutor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        // 设置任务队列容量，用于缓冲等待执行的任务
        threadPoolTaskExecutor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        // 设置线程空闲时间，当线程数超过核心线程数时，多余空闲线程的存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
        // 设置线程名称前缀，便于识别和调试线程池中的线程
        threadPoolTaskExecutor.setThreadNamePrefix("spring默认线程池-");
        // 设置拒绝执行处理器，当线程池和队列都满时，采用调用者运行策略处理新任务
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 设置关闭时是否等待任务完成，确保优雅关闭线程池
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        // 初始化线程池，完成所有配置参数的生效
        threadPoolTaskExecutor.initialize();

        return threadPoolTaskExecutor;
    }

}
